#include <memory>
#include <iostream>
#include <algorithm>
#include "TcpServer.hpp"
#include "comm.hpp"
#include "Daemon.hpp"
#include "Translate.hpp"
TransformNS::Translate trans;

void Interact(int sockfd, std::string &out, const std::string &in)
{
    char buffer[1024];
    ssize_t n = read(sockfd, buffer, sizeof(buffer) - 1);
    if (n > 0)
    {
        buffer[n] = 0;
        lg.LogMessage(Debug, "server send %s...", in.c_str());
        write(sockfd, in.c_str(), sizeof(in));
    }
    else if (n == 0)
    {
        lg.LogMessage(Debug, "client quit...,read over");
    }
    else
    {
        lg.LogMessage(Error, "read socket error,code:%d,error string:%s", errno, strerror(errno));
    }
}


void Translate(int sockfd, InetAddr addr)
{
    lg.LogMessage(Debug, "%s select %s success,sockfd %d", addr.PrintDebug().c_str(), "translate", sockfd);
    char wordbuffer[128];
    ssize_t n=read(sockfd,wordbuffer,sizeof(wordbuffer)-1);
    if(n>0)
    {
        wordbuffer[n]=0;
        lg.LogMessage(Debug,"[%s]say#%s",addr.PrintDebug().c_str(),wordbuffer);
    }
    std::string explain =trans.Excuse(wordbuffer);
    write(sockfd,explain.c_str(),explain.size());

    lg.LogMessage(Debug,"[%s]say %s translate-> %s",addr.PrintDebug().c_str(),wordbuffer,explain.c_str());

}

// 心跳机制
// 客户端发什么，就传回Pong
void Ping(int sockfd, InetAddr addr)
{
    lg.LogMessage(Debug, "%s select %s success,sockfd %d", addr.PrintDebug().c_str(), "ping", sockfd);

    std::string message;
    Interact(sockfd, message, "Pong");
}

void Transform(int sockfd, InetAddr addr)
{
    lg.LogMessage(Debug, "%s select %s success,sockfd %d", addr.PrintDebug().c_str(), "transform", sockfd);

    char buffer[128];
    ssize_t n = read(sockfd, buffer, sizeof(buffer) - 1);
    if (n > 0)
        buffer[n] = 0;
    lg.LogMessage(Debug,"[%s]say#%s",addr.PrintDebug().c_str(),buffer);
    std::string message = buffer;
    std::transform(message.begin(), message.end(), message.begin(), [](char c)
                   { return std::toupper(c); });
    lg.LogMessage(Debug, "from %s:%s toupper %s", addr.PrintDebug().c_str(), buffer, message.c_str());
    write(sockfd, message.c_str(), message.size());
}

void Usage(const std::string proc)
{
    std::cout << "Usage :\n\t" << proc << "server.port" << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(Usage_err);
    }

    Daemon(false,false);
    uint16_t port = std::stoi(argv[1]);
    std::unique_ptr<TcpServer> tsv = std::unique_ptr<TcpServer>(new TcpServer(port));

    tsv->RegisterFunc("ping", Ping);
    tsv->RegisterFunc("transform", Transform);
    tsv->RegisterFunc("translate",Translate);
    tsv->Init();
    tsv->Start();
    return 0;
}